// 地图初始化与核心实例管理

// hooks/useMap.ts
import { useEffect, useState } from 'react';

type MapConfig = {
  container: string;
  center: AMap.LngLat;
  zoom?: number;
  plugins?: string[];
};

export const useMap = (config: MapConfig) => {
  const [map, setMap] = useState<AMap.Map | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    if (!window.AMap) {
      setError(new Error('高德地图 API 未加载'));
      return;
    }else{
      console.log('高德地图 API 已加载');
    }

    try {
      const instance = new AMap.Map(config.container, {
        center: config.center,
        zoom: config.zoom || 13,
        plugins: config.plugins || [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.OverView',
          'AMap.MapType',
          'AMap.Geolocation',
          'AMap.PolyEditor',
          'AMap.CircleEditor',
          'AMap.Geocoder',
          'AMap.PlaceSearch',
          'AMap.Driving',
          'AMap.Transfer',
          'AMap.Walking',
          'AMap.Riding',
          'AMap.Polygon',
          'AMap.Polyline',
          'AMap.Marker',
          'AMap.InfoWindow',
          'AMap.ControlBar',
          'AMap.IndoorMap',
          'AMap.CitySearch',
          'AMap.Autocomplete',
        ],
      });
      setMap(instance);
    } catch (err) {
      setError(err as Error);
    } finally {
      setLoading(false);
    }

    return () => {
      if (map) map.destroy();
    };
  }, []);

  return { map, loading, error };
};